package cn.kgc.easybuy.utils;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.Random;

/**
 * @program: yingzi-wants-to-sleep
 * @description:
 * @author: 敖成
 * @create: 2025-09-11 16:29
 **/

public class SendMailUtil {
    private String host = "smtp.qq.com"; // QQ邮箱SMTP服务器
    private String port = "587"; // 端口号
    private static String from = "2503780894@qq.com"; // 发件人邮箱
    private  static String authCode = "solugqcjoypldigd"; // 授权码

    private Session session;

    /**
     * 构造方法
     */
    public SendMailUtil() {
        initSession();
    }

    /**
     * 初始化邮件会话
     */
    private void initSession() {
        // 配置属性
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true"); // 需要认证
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密
        props.put("mail.smtp.host", host); // SMTP服务器地址
        props.put("mail.smtp.port", port); // SMTP端口

        // 创建会话
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, authCode);
            }
        });

    }

    /**
     * 发送纯文本邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @return 发送成功返回true，否则返回false
     */
    public boolean sendTextEmail(String to, String subject, String content) {
        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送HTML格式邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param htmlContent HTML格式的邮件内容
     * @return 发送成功返回true，否则返回false
     */
    public boolean sendHtmlEmail(String to, String subject, String htmlContent) {
        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // 设置HTML内容
            message.setContent(htmlContent, "text/html;charset=utf-8");

            // 发送邮件
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

}
